package com.niiwoo.civet.trade.service.local.kaola;

import com.lycheepay.gateway.client.dto.QueryTradeRecordResultDTO;
import com.lycheepay.gateway.client.dto.TradeRecord;
import com.niiwoo.civet.trade.dao.entity.KaoLaRealRepayment;
import com.niiwoo.civet.trade.dao.entity.KaolaRepayOrder;
import com.niiwoo.civet.trade.dao.entity.KaolaWithholdOrder;
import com.niiwoo.civet.trade.dao.mapper.KaolaRepayOrderMapper;
import com.niiwoo.civet.trade.dto.kaola.NotifyRepaymentResult;
import com.niiwoo.civet.trade.dto.kaola.response.GetRepayResultResponse;
import com.niiwoo.civet.trade.service.local.kaola.newrepay.KaoLaLiCaiApplyForKFTService;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author daizhiyue
 * @description 考拉理财还款回调--查询状态为处理中的还款请求，根据查询结果更新还款结果.
 * @date 2017-1-12
 */
@Slf4j
@Service
public class KaoLaRepayBackJobDealService {
    private static final String jobName = "KaoLaLiCaiRepaymentResultJob";

    @Autowired
    private KaoLaLiCaiGetRepayResultService kaoLaLiCaiGetRepayResultService;

    @Autowired
    private KaoLaLiCaiApplyService kaoLaLiCaiApplyService;

    @Autowired
    private KaolaRepayOrderMapper kaolaRepayOrderMapper;

    /**
     * 半个小时的毫秒数,
     */
    private static final long HALF_HOUR_MILLI_SECONDS = 30 * 60 * 1000;


    public void dealRepayBackFailJob() {
        log.info(jobName + "*******KaoLaRepayBackJobDealService*******job start");
        List<KaoLaRealRepayment> list = kaoLaLiCaiGetRepayResultService.selectNeedGetRepayResultList();
        for (KaoLaRealRepayment payment : list) {
            try {
                GetRepayResultResponse response = kaoLaLiCaiGetRepayResultService.getRepayResult(payment.getSerialNo(),
                        payment.getProjectId().toString());
                if (null == response) {
                    log.info("请求查询还款结果超时!repay_serial_no：{},subject_id:{}", payment.getSerialNo(), payment.getProjectId().toString());
                } else {
                    if ("0".equals(response.getCode())) {
                        Byte repayType = Byte.parseByte(response.getRepay_type().toString());
                        Integer status = response.getStatus();
                        String creditor_attorn = response.getCreditor_attorn() == null ? ""
                                : response.getCreditor_attorn();
                        NotifyRepaymentResult repaymentResult = new NotifyRepaymentResult();
                        repaymentResult.setSubject_id(payment.getProjectId() + "");
                        repaymentResult.setSerial_no(payment.getSerialNo());
                        repaymentResult.setRepay_no(payment.getRepayNo());
                        repaymentResult.setIs_passive(payment.getIsPassive() == 1 ? false : true);
                        repaymentResult.setAmount(response.getAmount());
                        repaymentResult.setPrincipal(response.getPrincipal());
                        repaymentResult.setOverdue_interest(response.getOverdue_interest());
                        repaymentResult.setInterest(response.getInterest());
                        repaymentResult.setInterest_split(response.getInterest_split());
                        repaymentResult.setStatus(status);
                        repaymentResult.setType(repayType);
                        repaymentResult.setMsg(response.toString());
                        repaymentResult.setCreditor_attorn(creditor_attorn);
                        kaoLaLiCaiApplyService.notifyRepaymentForJob(repaymentResult);
                    } else {
                        log.info("查询订单失败!repay_serial_no：{},subject_id:{}", payment.getSerialNo(), payment.getProjectId().toString());
                    }
                }
            } catch (Exception e) {
                log.error(jobName, e);
            }
        }
        log.info(jobName + "*******KaoLaRepayBackJobDealService*******job end");
    }

    @Autowired
    private KaoLaLiCaiApplyForKFTService kaoLaLiCaiApplyForKFTService;

    public void dealRepayBackDealingForKFTJob() {
        log.info(jobName + "*******KaoLaRepayBackJobDealService*******dealRepayBackDealingForKFTJob start");
        List<KaolaWithholdOrder> list = kaoLaLiCaiGetRepayResultService.selectNeedDealKaolaWithholdOrderList();
        for (KaolaWithholdOrder kaolaWithholdOrder : list) {
            try {
                kaoLaLiCaiApplyForKFTService.notifyRepayment(kaolaWithholdOrder);
            } catch (Exception e) {
                log.error(jobName, e);
            }
        }

        List<KaolaWithholdOrder>  mayRetryList = kaoLaLiCaiGetRepayResultService.selectNeedSetFail();
        for (KaolaWithholdOrder kaolaWithholdOrder : mayRetryList) {
            try {

                // 超过6小时后还未拉取到成功的结果则认为最终失败
                if (new DateTime(kaolaWithholdOrder.getTradeTime()).plusHours(6).isBeforeNow()) {
                    kaoLaLiCaiGetRepayResultService.updateExceptionFail(kaolaWithholdOrder);
                }
            } catch (Exception e) {
                log.error(jobName +" updateExceptionFail", e);
            }
        }

        List<KaolaWithholdOrder> listForStatusNull = kaoLaLiCaiGetRepayResultService.selectStatusNullKaolaWithholdOrderList();
        for (KaolaWithholdOrder kaolaWithholdOrder : listForStatusNull) {
            if(System.currentTimeMillis() - kaolaWithholdOrder.getCreateTime().getTime() > HALF_HOUR_MILLI_SECONDS) {
                try {
                    kaoLaLiCaiApplyForKFTService.notifyRepayment(kaolaWithholdOrder);
                } catch (Exception e) {
                    log.error(jobName + "listForStatusNull", e);
                }
            }
        }

        log.info(jobName + "*******KaoLaRepayBackJobDealService*******dealRepayBackDealingForKFTJob end");
    }
    public void dealWithholdSuccessBackDealingForKFTJob() {
        log.info(jobName + "*******KaoLaRepayBackJobDealService*******dealWithholdBackDealingForKFTJob start");
        List<KaolaWithholdOrder> list = kaoLaLiCaiGetRepayResultService.selectTradeWithholdOrderList();
        if (list != null) {
            for (KaolaWithholdOrder withholdOrder : list) {
                QueryTradeRecordResultDTO recordResultDTO = new QueryTradeRecordResultDTO();
                List<TradeRecord> details = new ArrayList<>();
                TradeRecord tradeRecord = new TradeRecord();
                tradeRecord.setErrorCode(withholdOrder.getErrorCode());
                tradeRecord.setFailureDetails(withholdOrder.getFailureDetails());
                tradeRecord.setStatus(String.valueOf(withholdOrder.getStatus()));
                tradeRecord.setBankReturnTime(new DateTime(withholdOrder.getBankReturnTime()).toString("yyyyMMddHHmmss"));
                details.add(tradeRecord);
                recordResultDTO.setDetails(details);
                kaoLaLiCaiApplyForKFTService.notifyRepayment(withholdOrder, recordResultDTO);
                KaolaRepayOrder kaolaRepayNewOrder = new KaolaRepayOrder();
                KaolaRepayOrder kaolaRepayOrder = kaolaRepayOrderMapper.selectByPrimaryKey(withholdOrder.getRepayOrderId());
                if (kaolaRepayOrder != null && kaolaRepayOrder.getRetryTimes() <= 3) {
                    kaolaRepayNewOrder.setRetryTimes(kaolaRepayOrder.getRetryTimes() + 1);
                }
                kaoLaLiCaiGetRepayResultService.updateByPrimaryKeySelective(kaolaRepayNewOrder);
            }
        }
        log.info(jobName + "*******KaoLaRepayBackJobDealService*******dealRepayBackDealingForKFTJob end");
    }

}
